<?php
/**
* TopSites - Компонент каталога ссылок для Joostina CMS.
* @author:      Лаборатория сайтов, http://sitelab.net.ru
* @version:     1.9
* @release:     2010.02.07
* @package:     com_topsites
* @copyright:   (C) 2010 http://sitelab.net.ru,  see /administrator/components/com_topsites/copyright.php
* @license:     http://www.gnu.org/copyleft/gpl.html GNU/GPL
**/

defined( '_VALID_MOS' ) or die( '' );

if (!defined('topsites_BASE'))  { DEFINE( 'topsites_BASE', 	$mosConfig_absolute_path.'/components/com_topsites'); }
if (!defined('topsites_ADMIN')) { DEFINE( 'topsites_ADMIN', $mosConfig_absolute_path.'/administrator/components/com_topsites'); }
if (!defined('topsites_URL'))   { DEFINE( 'topsites_URL', 	$mosConfig_live_site.'/components/com_topsites'); }


if (!($acl->acl_check( 'administration', 'edit', 'users', $my->usertype,
'components', 'all' )
| $acl->acl_check( 'administration', 'edit', 'users', $my->usertype,
'components', 'com_topsites' ))) {
mosRedirect( 'index2.php', _NOT_AUTH );
}

require_once ($mainframe->getPath( 'admin_html' ) );
require_once ($mainframe->getPath( 'class' ) );
include_once (topsites_BASE.'/language/russian.php');
include_once (topsites_BASE.'/includes/topsites.tools.php');

$refusolcheckbox = mosGetParam( $_REQUEST, 'refusolcheckbox', 0 );
$refusol = mosGetParam( $_REQUEST, 'refusol', '' );
$id = mosGetParam( $_REQUEST, 'cid', array(0) );
$linkid = mosGetParam( $_REQUEST, 'linkid', '' );
$userid = mosGetParam( $_REQUEST, 'userid', 0 );

if (!is_array( $id ))
	{
	   $id = array($id);
	}

switch ($act)
{
   case 'categories' :
   switch($task) 
   {
      case 'new' :
	  AdminEditCategoriestopsites($option,0);
	  break;
	  
	  case 'edit' :
	  AdminEditCategoriestopsites($option,$id);
	  break;
	  
	  case 'save' :
	  AdminSaveCategoriestopsites();
	  break;
	  
	  case 'delete' :
	  AdminDeleteCategoriestopsites($option, $id);
	  break;
	  
	  case 'publish' :
	  AdminPublishCategoriestopsites($option, '1', $id);
	  break;
	  
	  case 'unpublish' :
	  AdminPublishCategoriestopsites($option, '0', $id);
	  break;
	  
	  case 'orderup' :
	  AdminOrderCategoriestopsites( intval($id[0]), -1);
	  break;
	  
	  case 'orderdown' :
	  AdminOrderCategoriestopsites( intval($id[0]), 1);
	  break;
	  
	  case 'accesspublic':
	  AdminAccessCategoriestopsites( intval( $id[0] ), 0, $section );
	  break;
	  
	  case 'accessregistered':
	  AdminAccessCategoriestopsites( intval( $id[0] ), 1, $section );
	  break;
	  
	  case 'accessspecial':
	  AdminAccessCategoriestopsites( intval( $id[0] ), 2, $section );
	  break;
	  
	  default :
	  AdminListCategoriestopsites($option);
	  break;
   }
   break;
   
   case 'settings' :
   switch ($task)
   {
      case 'save' :
	  AdminSaveSettingstopsites();
	  break;
	  
	  case 'cancel' :
	  AdminCancel();
	  break;
	  
	  default:
	  AdminListSettingstopsites($option);
	  break;
   }
   break;
   
   case 'help' :
   switch ($task)
   {
      
	  case 'cancel' :
	  AdminCancel();
	  break;
	  
	  default :
	  AdminHelptopsites();
	  break;
   }
   break;
   
   default :
   switch($task) 
   {
      case 'new' :
	  AdminEdittopsites($option,'');
	  break;
	  	   
	  case 'edit' :
	  AdminEdittopsites($option, $id);
	  break;
	  
	  case 'owner' :
	  AdminListUserstopsites($option);
	  break;
	  
	  case 'choice' :
	  AdminChoiceUserstopsites($option);
	  break;
	  
	  case 'save' :
	  AdminSavetopsites($option);
	  break;
	  
	  case 'delete' :
	  AdminDeletetopsites ($option, $id);
	  break;
	  
	  case 'publish' :
	  AdminPublishtopsites($option, '1', $id);
	  break;
	  
	  case 'unpublish' :
	  AdminPublishtopsites($option, '0', $id);
	  break;
	  
	  case 'refusal':
	  AdminRefusalApprovedtopsites($linkid, $controlofid);
	  break;
	   
	  case 'refusalmail':
	  AdminRefusalMailtopsites($linkid, $controlofid, $refusol);
	  break;
	  
	   case 'check':
	  linksCheck($option, $id);
	  break;
	  
	  default:
	  AdminListtopsites($option);
	  break;
   }
   break;
}	
   /*
   * Фунция для проверки обраток - адаптер
   */
   function linksCheck( $option, $ids) {
	$database = $mainframe->_db;
       if (!defined('topsites_ADMIN')) { DEFINE( 'topsites_ADMIN', $mosConfig_absolute_path.'/administrator/components/com_topsites'); }
       require_once(topsites_ADMIN."/topsites.config.php");
	foreach ($ids as $id){
		$sql="SELECT url_back FROM #__topsites WHERE id=$id";
		$database->setQuery($sql);
		$url_back=$database->loadResult();
		
			if (! isURLonPage($url_back, $сheck_link)){
				$check=", check_back=0";
				$msg=_TL_LINK_CHECK_BED;
			} else {
				$check=", check_back=1";
				$msg=_TL_LINK_CHECK_GOOD;
			}
		$sql="UPDATE #__topsites SET date_check='".date( "Y-m-d H:i:s" )."'$check WHERE id=$id";
		$database->setQuery($sql);
		$database->query();
		
	}
   mosRedirect("index2.php?option=com_topsites", $msg);
  }



		 
   /*
   * Функция по обратоной замене тегов [icq] и [email]
   */
   function ReplaceTegs( $string ) {
   $string = preg_replace('/\\n/', '<br>',$string);	
   $string = preg_replace('/\[ICQ\](.+?)\[\/ICQ\]/', '<a href="http://web.icq.com/whitepages/message_me/1,,,00.icq?uin=\1&action=message"><img src=http://wwp.icq.com/scripts/online.dll?icq=\1&img=5 border=0 alt="Отправить сообщение" border=0>(\1)</a>',$string);
   $string = preg_replace('/\[Email\](.+?)\[\/Email\]/', '<a href="mailto:\1">\1</a>',$string);

   return $string;	
   }
function AdminListtopsites($option) {
  $mainframe = &mosMainFrame::getInstance();
   $database = $mainframe->_db;
   global $mosConfig_list_limit, $mosConfig_absolute_path ;
   
   $limit      = intval( $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit ) );
   $limitstart = intval( $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 ) );
   
   $query = "SELECT COUNT(*)"
   . "\n FROM #__topsites"
   ;
   $database->setQuery( $query );
   $total = $database->loadResult();
   
   require_once( $mosConfig_absolute_path.'/administrator/includes/pageNavigation.php' );
   $pageNav = new mosPageNav( $total, $limitstart, $limit );
   
   $query="SELECT t . *, u.name as username , c.name AS catname FROM #__topsites AS t"
   ."\n LEFT JOIN #__users as u ON (t.userid = u.id)" 
   ."\n LEFT JOIN #__topsites_categories AS c"		  
   ."\n ON t.catid = c.id"
   ."\n ORDER BY t.date DESC"
   ."\n LIMIT $pageNav->limitstart, $pageNav->limit"
   ;
   $database->setQuery($query);
   $rows = $database -> loadObjectList();
	//Заменим теги 

   foreach ($rows as $key=>$row){
	
   	if (!empty ($row->contact)) {
	
	$rows[$key]->contact=ReplaceTegs($row->contact);
	//$row->contact=ReplaceTegs($row->contact);
	}
   }
   Admin_HTML_topsites::AdminListtopsites($option, $rows, $pageNav); 
}

function AdminEdittopsites($option, $id) 
{
   $database = &database::getInstance();
   global $userid, $my;
   
   $row = new topsites($database);
         
   if($id)
   {
      $row -> load($id[0]);
	  
   }
         
   $lists['catid'] = AdminComponentCategory( 'catid', intval($row->catid), NULL );
   
   //Определение владельца
   if(!$userid){
		$userid = $row->userid;
		if ($userid===''){
			$userid = $my->id;
		}	
	}
    $query = "SELECT name"
	. "\n FROM #__users"
	. "\n WHERE id=$userid"
	;
    $database->setQuery( $query );
    $owner = $database->loadResult();
   
   Admin_HTML_topsites::AdminEdittopsites($option, $row, $lists, $owner, $userid);
}

function AdminListUserstopsites($option) {
  $mainframe = &mosMainFrame::getInstance();
  $database = $mainframe->_db;
	global $my, $acl, $mosConfig_list_limit, $linkid, $mosConfig_absolute_path;

	$filter_type	= $mainframe->getUserStateFromRequest( "filter_type{$option}", 'filter_type', 0 );
	$filter_logged	= intval( $mainframe->getUserStateFromRequest( "filter_logged{$option}", 'filter_logged', 0 ) );
	$limit 			= intval( $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit ) );
	$limitstart 	= intval( $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 ) );
	$search 		= $mainframe->getUserStateFromRequest( "search{$option}", 'search', '' );
	if (get_magic_quotes_gpc()) {
		$filter_type	= stripslashes( $filter_type );
		$search			= stripslashes( $search );
	}
	$where 			= array();

	if (isset( $search ) && $search!= "") {
		$searchEscaped = $database->getEscaped( trim( strtolower( $search ) ) );
		$where[] = "(a.username LIKE '%$searchEscaped%' OR a.email LIKE '%$searchEscaped%' OR a.name LIKE '%$searchEscaped%')";
	}
	if ( $filter_type ) {
		if ( $filter_type === 'Public Frontend' ) {
			$where[] = "(a.usertype = 'Registered' OR a.usertype = 'Author' OR a.usertype = 'Editor'OR a.usertype = 'Publisher')";
		} else if ( $filter_type === 'Public Backend' ) {
			$where[] = "(a.usertype = 'Manager' OR a.usertype = 'Administrator' OR a.usertype = 'Super Administrator')";
		} else {
			$where[] = "a.usertype = LOWER( " . $database->Quote( $filter_type ) . " )";
		}
	}
	if ( $filter_logged === 1 ) {
		$where[] = "s.userid = a.id";
	} else if ($filter_logged === 2) {
		$where[] = "s.userid IS NULL";
	}

	// exclude any child group id's for this user
	$pgids = $acl->get_group_children( $my->gid, 'ARO', 'RECURSE' );

	mosArrayToInts( $pgids );
	if (is_array( $pgids ) && count( $pgids ) > 0) {
		$where[] = '( a.gid != '  . implode( ' OR a.gid != ', $pgids ) . ' )';
	}

	$query = "SELECT COUNT(a.id)"
	. "\n FROM #__users AS a";

	if ($filter_logged == 1 || $filter_logged == 2) {
		$query .= "\n INNER JOIN #__session AS s ON s.userid = a.id";
	}

	$query .= ( count( $where ) ? "\n WHERE " . implode( ' AND ', $where ) : '' )
	;
	$database->setQuery( $query );
	$total = $database->loadResult();

	require_once( $mosConfig_absolute_path.'/administrator/includes/pageNavigation.php' );
	$pageNav = new mosPageNav( $total, $limitstart, $limit  );

	$query = "SELECT a.*, g.name AS groupname"
	. "\n FROM #__users AS a"
	. "\n INNER JOIN #__core_acl_aro AS aro ON aro.value = a.id"	// map user to aro
	. "\n INNER JOIN #__core_acl_groups_aro_map AS gm ON gm.aro_id = aro.aro_id"	// map aro to group
	. "\n INNER JOIN #__core_acl_aro_groups AS g ON g.group_id = gm.group_id";

	if ($filter_logged == 1 || $filter_logged == 2) {
		$query .= "\n INNER JOIN #__session AS s ON s.userid = a.id";
	}

	$query .= (count( $where ) ? "\n WHERE " . implode( ' AND ', $where ) : "")
	. "\n GROUP BY a.id"
	;
	$database->setQuery( $query, $pageNav->limitstart, $pageNav->limit );
	$rows = $database->loadObjectList();

	if ($database->getErrorNum()) {
		echo $database->stderr();
		return false;
	}

	$template = 'SELECT COUNT(s.userid) FROM #__session AS s WHERE s.userid = ';
	$n = count( $rows );
	for ($i = 0; $i < $n; $i++) {
		$row = &$rows[$i];
		$query = $template . (int) $row->id;
		$database->setQuery( $query );
		$row->loggedin = $database->loadResult();
	}

	// get list of Groups for dropdown filter
	$query = "SELECT name AS value, name AS text"
	. "\n FROM #__core_acl_aro_groups"
	. "\n WHERE name != 'ROOT'"
	. "\n AND name != 'USERS'"
	;
	$types[] = mosHTML::makeOption( '0', '- Выбор группы -' );
	$database->setQuery( $query );
	$types = array_merge( $types, $database->loadObjectList() );
	$lists['type'] = mosHTML::selectList( $types, 'filter_type', 'class="inputbox" size="1" onchange="document.adminForm.submit( );"', 'value', 'text', "$filter_type" );

	// get list of Log Status for dropdown filter
	$logged[] = mosHTML::makeOption( 0, '- Выбор статуса - ');
	$logged[] = mosHTML::makeOption( 1, 'Logged In');
	$lists['logged'] = mosHTML::selectList( $logged, 'filter_logged', 'class="inputbox" size="1" onchange="document.adminForm.submit( );"', 'value', 'text', "$filter_logged" );
	
	Admin_HTML_topsites::AdminListUserstopsites($rows, $pageNav, $search, $option, $lists, $linkid);

}

function AdminSavetopsites($option) {
   $database = &database::getInstance();
   global $mosConfig_sitename, $mosConfig_mailfrom, $mosConfig_fromname, $refusolcheckbox, $refusol;
  
   $row = new topsites($database);															
   
   if (!$row -> bind($_POST)) 
   {  echo "<script> alert('".$row -> getError()."'); window.history.go(-1); </script>\n";
      exit();
   }	 
					  
   $linkid = $row->id;;
   $row->date = date( "Y-m-d H:i:s" );
  
   if (!$row -> check())
   {   echo "<script> alert('".$row -> getError()."'); window.history.go(-1); </script>\n";
       exit();	
   }
      
   if (!$row -> store()) 
   {  echo "<script> alert('".$row -> getError()."'); window.history.go(-1); </script>\n";
	  exit();	
   }
   
  $fname = topsites_BASE.'/favicon/favicon_'.$row->id.'.png';
  savefavicon($row->url,$fname);

   
   if ($refusolcheckbox == 1){
   
    //Очистка массива
	$row = array();
			
	//Получение данных ссылки
	$query = ( "SELECT  t.*, u.email, tc.name AS catname"
	."\n FROM #__topsites AS t LEFT OUTER JOIN #__users AS u "
	."\n ON t.userid = u.id LEFT OUTER JOIN #__topsites_categories AS tc "
	."\n ON t.catid = tc.id "
	."\n WHERE t.id = $linkid " )
	;
	$database->setQuery( $query );
    $rows = $database->loadObjectList();
	foreach ($rows as $row);
	
	//отправка письма пользователю
		$subject = $mosConfig_sitename." - "._TL_REFUSAL_APPROVED;
		$text = "\r\n"._TL_HELLO;
		$text.= "\r\n\r\n"._TL_YOU_LINK_ADD.$mosConfig_sitename;
		$text.= "\r\n\r\n"._TL_YUU_LINK_REFUSAL_APPROVED;
	    $text.= "\r\n\r\n"._TL_REASON.': '.$refusol;
		$text.= "\r\n\r\n"._TL_YOU_LINK;
		$text.= "\r\n"."______________________________";
		$text.= "\r\n\r\n"._TL_CATEGORY.': '.$row->catname;
		$text.= "\r\n\r\n"._TL_LINK.': '.$row->name;
		$text.= "\r\n\r\n"._TL_DESCRIPTION_LINK.': '.$row->description;
		$text.= "\r\n\r\n"._TL_URL_LINK.': '.$row->url;
		$text.= "\r\n\r\n"._TL_URL_BACK_LINK.': '.$row->url_back;
		$text.= "\r\n\r\n"."______________________________";
		$text.= "\r\n\r\n"._TL_WE_THANK_YOU.$mosConfig_sitename;
		$text.= "\r\n\r\n"."______________________________";
					
		mosMail( $mosConfig_mailfrom, $mosConfig_fromname, $row->email, $subject,$text);
	}
       
  mosRedirect("index2.php?option=com_topsites", _TL_SAVED);
}

function AdminDeletetopsites($option, $id) {  
$database = &database::getInstance();

   if (!is_array($id) || count($id) < 1) 
   {  echo "<script> alert('"._TL_SELECT_DELETE."'); window.history.go(-1);</script>\n";
	  exit();
   }

   if (count($id))
   {
      $ids = implode(',', $id);
	  $database->setQuery("SELECT * FROM #__topsites \nWHERE id IN ($ids)");
      $rows = $database -> loadObjectList();
      foreach ($rows as $row)
      {
		// Удалим иконки
		unlink(topsites_BASE.'/favicon/favicon_'.$row->id.'.png');
		// Удалим картинки 
		unlink(topsites_BASE."/adimages/".$row->image);
		unlink(topsites_BASE."/adimages/thumbs/".$row->image);
      }
	  
	  $database->setQuery("DELETE FROM #__topsites \nWHERE id IN ($ids)");
   }
   
   if (!$database->query()) {
      echo "<script> alert('".$database -> getErrorMsg()."'); window.history.go(-1); </script>\n";
   }

   mosRedirect("index2.php?option=com_topsites");
}

function AdminPublishtopsites( $option, $publish=1 ,$id ) {  
$database = &database::getInstance();
global $my;
   
   if (!is_array( $id ) || count( $id ) < 1) 
   {
      $action = $publish ? 'publish' : 'unpublish';
	  echo "<script> alert('Select an item to $action'); window.history.go(-1);</script>\n";
	  exit;
   }
   
   $ids = implode( ',', $id );
   $database->setQuery( "UPDATE #__topsites SET published='$publish'"
   . "\n WHERE id IN ($ids)")
   ;
   if (!$database->query()) 
   {
      echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
	  exit();
   }
   mosRedirect( "index2.php?option=com_topsites" );
}

function AdminListCategoriestopsites($option) 
{
    $mainframe = &mosMainFrame::getInstance();
	$database = $mainframe->_db;
	global $mosConfig_list_limit;
   $limit      = intval( $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit ) );
   $limitstart = intval( $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 ) );
   
   $query = "SELECT COUNT(*)"
   . "\n FROM #__topsites_categories"
   ;
   $database->setQuery( $query );
   $total = $database->loadResult();
   
   require_once( $GLOBALS['mosConfig_absolute_path'] . '/administrator/includes/pageNavigation.php' );
   $pageNav = new mosPageNav( $total, $limitstart, $limit );
   
   $query="SELECT c.*,g.name as groupname FROM #__topsites_categories AS c"
   ."\n LEFT JOIN #__groups AS g ON g.id = c.access"
   ."\n GROUP BY c.id"
   ."\n ORDER BY c.ordering,c.name"
   ."\n LIMIT $pageNav->limitstart, $pageNav->limit"
   ;
   $database->setQuery( $query );
   $rows=$database->loadObjectList();
   
   Admin_HTML_topsites :: AdminListCategoriestopsites($option,$pageNav,$rows) ;
}  

////			   
function editCatg( $uid, $option ) {
$database = &database::getInstance();
global $my;
	$row = new mosCatgs( $database );
	$row->load( $uid );

    $orders    = mosGetOrderingList( "select ordering as value, name as text from #__datsogallery_catg order by ordering desc" );

	$orderlist = mosHTML::selectList( $orders, 'ordering', 'class="inputbox"', 'value', 'text', intval( $row->ordering ) );
    $yesno[]   = mosHTML::makeOption( '0', _DG_NO );
	$yesno[]   = mosHTML::makeOption( '1', _DG_YES );
    $publist   = mosHTML::selectList( $yesno, 'published', 'class="inputbox"', 'value', 'text', $row->published );
    $database->setQuery( "select id as value, name as text from #__groups order by id" );
	$groups    = $database->loadObjectList();
    $glist     = mosHTML::selectList( $groups, 'access', 'class="inputbox"', 'value', 'text', intval( $row->access ) );
    $row->parent = $row->parent > 1;
    $Lists["catgs"] = ShowDropDownCategoryList("$row->parent","parent","dests");
	HTML_datsogallery::editCatg( $row, $publist, $option , $glist , $Lists, $orderlist );
}
////


function AdminEditCategoriestopsites($option, $uid)
{
   $database = &database::getInstance();
   
   $row = new topsitesCategories($database);
   if ($uid)
   {
      $row -> load($uid[0]);
   }
 
   $coptstr= "<OPTION VALUE=\"0\">- "._TL_SELECT_CAT." -</OPTION>\n";
   $lists['categories']= list_category($row->id,$row->cat_parent,'cat_parent','',$coptstr,'');
        
   $query = "SELECT ordering AS value, name AS text"
   . "\n FROM #__topsites_categories"	 
   . "\n WHERE cat_parent = '$row->cat_parent'"
   . "\n ORDER BY ordering" ;
     
   $lists['ordering'] = mosAdminMenus::SpecificOrdering($row, $uid, $query);
   $lists['access']	= mosAdminMenus::Access( $row );  
   
   $directory = '/images/stories';   // Папка с картинками используемая по умолчанию
   $javascript = "onchange=\"javascript:if (document.forms['adminForm'].image.options[selectedIndex].value!='') {document.imagelib.src='..$directory/' + document.forms['adminForm'].image.options[selectedIndex].value} else {document.imagelib.src='../images/blank.png'}\"";
   $lists['image'] = mosAdminMenus::Images( 'image', $row->image, $javascript);
   
   Admin_HTML_topsites :: AdminEditCategoriestopsites($option, $row, $lists);
}

function AdminSaveCategoriestopsites() {
   $database = &database::getInstance();
   
   $row = new topsitesCategories($database);
   
   if (!$row -> bind($_POST)) {
      echo "<script> alert('".$row -> getError()."'); window.history.go(-1); </script>\n";
	  exit();
   }
   
   if (!$row -> store()) {
      echo "<script> alert('".$row -> getError()."'); window.history.go(-1); </script>\n";
	  exit();	
   }
   
   $row->updateOrder();
   
   mosRedirect("index2.php?option=com_topsites&act=categories", _TL_SAVED);
}

function AdminDeleteCategoriestopsites($option, $id)
{
   $database = &database::getInstance();
	
   if (!is_array($id) || count($id) < 1) {
      echo "<script> alert('"._TL_SELECT_DELETE."'); window.history.go(-1);</script>\n";
	  exit();
   }

   if (count($id))  {
      $ids = implode(',', $id);
	  $database->setQuery("DELETE FROM #__topsites_categories \nWHERE id IN ($ids)");
   }			  
   
   if (!$database->query()) {
      echo "<script> alert('".$database -> getErrorMsg()."'); window.history.go(-1); </script>\n";
   }													
   
   mosRedirect("index2.php?option=com_topsites&act=categories");
}

function AdminPublishCategoriestopsites($option, $publish=1 ,$id) {
   $database = &database::getInstance();
   global $my;
   
   if (!is_array( $id ) || count( $id ) < 1) {
      $action = $publish ? 'publish' : 'unpublish';
	  echo "<script> alert('Select an item to $action'); window.history.go(-1);</script>\n";
	  exit;
   }
   
   $ids = implode( ',', $id );
   
   $database->setQuery( "UPDATE #__topsites_categories SET published='$publish'". "\nWHERE id IN ($ids)");
   if (!$database->query()) 
   {
      echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
	  exit();
   }

   mosRedirect( "index2.php?option=com_topsites&act=categories" );
}

function AdminOrderCategoriestopsites( $uid, $inc ) {
   $database = &database::getInstance();
   
   $row = new topsitesCategories ($database);
   $row->load( $uid );
   $row->move( $inc );
   
   mosRedirect( 'index2.php?option=com_topsites&act=categories' );  
}

function AdminAccessCategoriestopsites( $uid, $access, $section ) {
   $database = &database::getInstance();
   
   $row = new topsitesCategories ($database);
   
   $row->load( $uid );
   $row->access = $access;
   $row->store();
   
   mosRedirect( 'index2.php?option=com_topsites&act=categories' );
}

function AdminComponentCategory( $name, $active=NULL, $javascript=NULL, $order='ordering', $size=1, $sel_cat=1 ) {
   $database = &database::getInstance();
   
   $query = "SELECT id AS value, name AS text"
   . "\n FROM #__topsites_categories"
   . "\n WHERE published = 1"
   . "\n ORDER BY $order"
   ;
   $database->setQuery( $query );
   
   if ( $sel_cat ) 
   {
      $categories[] = mosHTML::makeOption( '0', _SEL_CATEGORY );
	  //$categories[] = mosHTML::makeOption( '0', "------------" );
	  $categories = array_merge( $categories, $database->loadObjectList() );
   }
   else
   {
      $categories = $database->loadObjectList();
   }
   
   if ( count( $categories ) < 1 ) 
   {
      mosRedirect( 'index2.php?option=com_linkdirectory&task=categories', _TL_ONECATPLS );
   }
   $category = mosHTML::selectList( $categories, $name, 'class="inputbox" size="'. $size 
   .'" '. $javascript, 'value', 'text', $active );
   
   return $category;
}


function AdminListSettingstopsites($option) {
	// Вытащим всех пользователей
 $database = &database::getInstance();
  
   $query = "SELECT id , name, gid, user_id as access "
   . "\n FROM #__users"
   . "\n LEFT JOIN #__topsites_users ON user_id=id"
   . "\n WHERE gid<25";
 // Только вот ненадо с Администратором играться
   $database->setQuery( $query );
   $users = $database->loadObjectList();
   Admin_HTML_topsites::AdminListSettingstopsites($option,$users );
}

function AdminSaveSettingstopsites() {
    $database = &database::getInstance();
   require_once( topsites_BASE.'/includes/sanitizer.class.php');
   
   $san = new HTML_Sanitizer;
   $configfile = topsites_ADMIN."/topsites.config.php";
   
   $tl_visitors_can_add		= $san->sanitize ( $_POST['tl_visitors_can_add']);
   $tl_to_demand_link_back 	= $san->sanitize ( $_POST['tl_to_demand_link_back']);
   $tl_use_bannercode  		= $san->sanitize ( $_POST['tl_use_bannercode']);				 
   $tl_max_tophits 		= $san->sanitize ( $_POST['tl_max_tophits']);	
   $tl_limit 		= $san->sanitize ( $_POST['tl_limit']);
   $tl_lenght 		= $san->sanitize ( $_POST['tl_lenght']);
   $tl_link_back 	= $san->sanitize ( $_POST['tl_link_back']);
   $tl_link_back_2 	= $san->sanitize ( $_POST['tl_link_back_2']);
   $сheck_link 		= $san->sanitize ( $_POST['сheck_link']);
   $tl_email_default= $san->sanitize ( $_POST['tl_email_default']);
   $numOfColumns 	= $san->sanitize ( $_POST['numOfColumns']);
   $tl_use_editor 	= $san->sanitize ( $_POST['tl_use_editor']);
   
   $tl_use_metakey  = $san->sanitize ( $_POST['tl_use_metakey']);
   $tl_use_metadesc = $san->sanitize ( $_POST['tl_use_metadesc']);
   $tl_ask_email 	= $san->sanitize ( $_POST['tl_ask_email']);
   $tl_use_captcha  = $san->sanitize ( $_POST['tl_use_captcha']);
   
   $tl_show_backurl = $san->sanitize ( $_POST['tl_show_backurl']);
   $tl_show_toolbar = $san->sanitize ( $_POST['tl_show_toolbar']);
   $tl_show_subcats = $san->sanitize ( $_POST['tl_show_subcats']);
   $tl_visitors_can_add_back = $san->sanitize ( $_POST['tl_visitors_can_add_back']);		   
   
   $numOfSubcatsToDisplay = $san->sanitize ( $_POST['numOfSubcatsToDisplay']);   
   $tl_text_for_backurl   = $san->sanitize ( $_POST['tl_text_for_backurl']);
   $def_img_size_x 		  = $san->sanitize ( $_POST['def_img_size_x']);
   $def_img_size_y		  = $san->sanitize ( $_POST['def_img_size_y']);
   $def_img_thumb_size_x  = $san->sanitize ( $_POST['def_img_thumb_size_x']);
   $def_img_thumb_size_y  = $san->sanitize ( $_POST['def_img_thumb_size_y']);
   $save_img_quality 	  = $san->sanitize ( $_POST['save_img_quality']);  
   $tl_show_hits 		  = $san->sanitize ( $_POST['tl_show_hits']);
   $tl_show_tophits 	  = $san->sanitize ( $_POST['tl_show_tophits']);
   $tl_ask_contact 	  = $san->sanitize ( $_POST['tl_ask_contact']);	
   $Users  			  = mosGetParam( $_REQUEST, 'Users', null );
   // Небудем заморачиваться, тупо все сбросим
	$database->setQuery( "DELETE FROM #__topsites_users");
	$database->query();
   // Добавим доступ юзверям
   if (!empty ($Users)){
	
	
   	foreach ($Users as $User){
		if (!empty ($User)){
			$database->setQuery( "INSERT INTO #__topsites_users (user_id) VALUES ($User)");
			$database->query();	
		}
	}
   }	
   unset ($san);	
  
   @chmod ($configfile, 0766);
   $permission = is_writable($configfile);
   if (!$permission) 
   {
      $mosmsg = _TL_CONFIG_NOT_WRITABLE;
	  mosRedirect("index2.php?option=com_topsites&act=settings",$mosmsg);
	  break;
   }

   $config = "<?php\n";
   $config .= "\$tl_visitors_can_add = \"$tl_visitors_can_add\";\n";
   $config .= "\$tl_limit         = \"$tl_limit\";\n";
   $config .= "\$tl_lenght        = \"$tl_lenght\";\n";
   $config .= "\$tl_link_back     = '$tl_link_back';\n";
   $config .= "\$tl_link_back_2   = '$tl_link_back_2';\n";
   $config .= "\$tl_to_demand_link_back = \"$tl_to_demand_link_back\";\n";
   $config .= "\$tl_use_bannercode = \"$tl_use_bannercode\";\n";   

   $config .= "\$tl_show_hits     = \"$tl_show_hits\";\n"; 	   
   $config .= "\$tl_show_tophits  = \"$tl_show_tophits\";\n"; 	   
   $config .= "\$tl_show_toolbar  = \"$tl_show_toolbar\";\n"; 	   
   $config .= "\$tl_max_tophits   = \"$tl_max_tophits\";\n"; 	   
   $config .= "\$tl_show_subcats  = \"$tl_show_subcats\";\n"; 	   
   $config .= "\$numOfSubcatsToDisplay = \"$numOfSubcatsToDisplay\";\n"; 	   
   
   $config .= "\$сheck_link = \"$сheck_link\";\n";
   $config .= "\$tl_email_default = \"$tl_email_default\";\n";
   $config .= "\$tl_show_backurl  = \"$tl_show_backurl\";\n";
   $config .= "\$tl_text_for_backurl = \"$tl_text_for_backurl\";\n";
   $config .= "\$numOfColumns  	  = \"$numOfColumns\";\n"; 
   $config .= "\$tl_use_editor 	  = \"$tl_use_editor\";\n"; 
   
   $config .= "\$tl_use_metakey   = \"$tl_use_metakey\";\n"; 
   $config .= "\$tl_use_metadesc  = \"$tl_use_metadesc\";\n"; 					  
   $config .= "\$tl_ask_email	  = \"$tl_ask_email\";\n"; 
   $config .= "\$tl_use_captcha   = \"$tl_use_captcha\";\n"; 
   
   $config .= "\$def_img_size_x   = \"$def_img_size_x\";\n"; 
   $config .= "\$def_img_size_y   = \"$def_img_size_y\";\n"; 
   $config .= "\$def_img_thumb_size_x = \"$def_img_thumb_size_x\";\n"; 
   $config .= "\$def_img_thumb_size_y = \"$def_img_thumb_size_y\";\n"; 
   $config .= "\$save_img_quality = \"$save_img_quality\";\n"; 
   $config .= "\$tl_ask_contact = \"$tl_ask_contact\";\n"; 	   
   $config .= "?>";
   
   if ($fp = fopen("$configfile", "w")) 
   {
      fputs($fp, $config, strlen($config));
	  fclose ($fp);
   }
   mosRedirect("index2.php?option=com_topsites&act=settings", _TL_SETTINGS_SAVED);
}

function AdminHelptopsites() {
	global $mosConfig_absolute_path;
	
	require_once ( topsites_ADMIN.'/help/help.html' );
}

function AdminCancel() 
{
   mosRedirect("index2.php?option=com_topsites",_TL_CANCEL);
}
/* --------------------------------------------------------	
// Проверка на наличия строки на странице (обратной ссылки)
// $url - где искать,  $check - что искать
// ----------------------------------------------------- */
function isURLonPage(&$url, $check){
		  	
  	// Проверка на правильность введенной ссылки (если нет протокола http:// будет добавлен)
	$url = checkurl($url);	  
 	if (strlen($url) < 5) return false;		  
	// Если	вкачестве обратной указана наша ссылка - жулики - выходим...
	if (strpos($url, strtolower(JPATH_SITE)) !== false)  return false;
	
	$ch_pre = curl_init();
	curl_setopt($ch_pre, CURLOPT_HEADER, 1);
	curl_setopt($ch_pre, CURLOPT_URL, $url);
	curl_setopt($ch_pre, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch_pre, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ch_pre, CURLOPT_FAILONERROR, 0);
	$content = curl_exec($ch_pre);
	curl_close($ch_pre);						
	
	// Почистим из страницы все замаскированные ссылки
    $content = preg_replace("/<!--(.*)--\s*>/siU", '', $content);
    $content = preg_replace("/<NOINDEX>(.*)<\/NOINDEX>/siU", '', $content);
    $content = preg_replace("/<script[^>]*>(.*)<\/script>/siU", '', $content);
    $content = preg_replace("/<style[^>]*>(.*)<\/style>/siU", '', $content);

	return  (strpos ( $content, $check) !== false);
}
echo '<hr><table width="100%"><tr><td align="center">'._TL_VERSION.'</td></tr></table>';

?>

<?php
/*
//=========================================================
// при изменении публикации сайта рассылала сообщение пользователям, 
// отключил, так-как считаю избыточной... 

function AdminPublishAtopsites( $option, $publish=1 ,$id )
{
   global $database, $my, $mosConfig_sitename, $mosConfig_mailfrom, $mosConfig_fromname, $mosConfig_live_site;
   
   if (!is_array( $id ) || count( $id ) < 1) 
   {
      $action = $publish ? 'publish' : 'unpublish';
	  echo "<script> alert('Select an item to $action'); window.history.go(-1);</script>\n";
	  exit;
   }
   
   $ids = implode( ',', $id );
   $database->setQuery( "UPDATE #__topsites SET published='$publish'"
   . "\n WHERE id IN ($ids)")
   ;
   if (!$database->query()) 
   {
      echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
	  exit();
   }
   
   $ids = implode( ',', $id );
   $database->setQuery( "SELECT id FROM #__topsites"
   . "\n WHERE id IN ($ids)")
   ;
   $rows = $database -> loadResultArray();
    
   for ($i = 0; $i < count($rows); $i++) {
   		$query = ( "SELECT  t.*, u.email, tc.name AS catname"
		."\n FROM #__topsites AS t LEFT OUTER JOIN #__users AS u "
		."\n ON t.userid = u.id LEFT OUTER JOIN #__topsites_categories AS tc "
		."\n ON t.catid = tc.id "
		."\n WHERE t.id = $rows[$i] " )
		;
		$database->setQuery( $query );
		$result = $database -> loadObjectList();
		foreach($result as $row);
	    //отправка письма пользователю
		$subject = $mosConfig_sitename." - "._TL_LINK_IS_ADD;
		$text = "\r\n"._TL_HELLO;
		$text.= "\r\n\r\n"._TL_YOU_LINK_ADD.$mosConfig_sitename;
		$text.= "\r\n\r\n"._TL_YUU_LINK_APPROVED;
	    $text.= "\r\n\r\n"._TL_TO_topsites.': '.$mosConfig_live_site."/index.php?option=com_topsites";
		$text.= "\r\n\r\n"._TL_YOU_LINK;
		$text.= "\r\n"."______________________________";
		$text.= "\r\n\r\n"._TL_CATEGORY.': '.$row->catname;
		$text.= "\r\n\r\n"._TL_LINK.': '.$row->name;
		$text.= "\r\n\r\n"._TL_DESCRIPTION_LINK.': '.$row->description;
		$text.= "\r\n\r\n"._TL_URL_LINK.': '.$row->url;
		$text.= "\r\n\r\n"._TL_URL_BACK_LINK.': '.$row->url_back;
		$text.= "\r\n\r\n"."______________________________";
		$text.= "\r\n\r\n"._TL_WE_THANK_YOU.$mosConfig_sitename;
		$text.= "\r\n\r\n"."______________________________";
					
		mosMail( $mosConfig_mailfrom,$mosConfig_fromname,$row->email,$subject,$text);
	}
	mosRedirect( "index2.php?option=com_topsites" );
   
}
*/

?>
